package com.yiwei.jmx.activity;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.yiwei.jmx.R;
import com.yiwei.jmx.api.Api;
import com.yiwei.jmx.api.bean.DealPhotoBean;
import com.yiwei.jmx.api.bean.UploadImageBean;
import com.yiwei.jmx.api.bean.ZhiMaCertBean;
import com.yiwei.jmx.api.bean.ZhiMaCertQueryBean;
import com.yiwei.jmx.base.BaseActivity;
import com.yiwei.jmx.constant.Const;
import com.yiwei.jmx.constant.FaceBitmap;
import com.yiwei.jmx.constant.UserInfoGlobal;
import com.yiwei.jmx.event.IdcardFaceEvent;
import com.yiwei.jmx.event.OnZhiMaEventMsg;
import com.yiwei.jmx.util.Dialog;
import com.yiwei.jmx.util.ImageUtil;
import com.yiwei.jmx.util.Network;
import com.yiwei.jmx.util.PreferenceUtils;
import com.yiwei.jmx.util.RxLifeUtil;
import com.yiwei.jmx.util.ToastUtil;
import com.yiwei.jmx.util.Util;
import com.yiwei.jmx.view.V19FrameLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.net.URLEncoder;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class FaceIdentityActivity extends BaseActivity {


    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.btn_wechat)
    ImageView btnWechat;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.layout_top)
    LinearLayout layoutTop;
    @BindView(R.id.btn_submit)
    TextView btnSubmit;
    private Unbinder unbiner;
    private boolean is_borrow_step;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_face_identity);
        initBar();
        setBarClick();
        unbiner = ButterKnife.bind(this);
        init();
        EventBus.getDefault().register(this);
    }

    private void init() {
        txtTitle.setText("人脸自拍");
        is_borrow_step = getIntent().getBooleanExtra("isFromLoan", false);
        if (is_borrow_step) {
            layoutTop.setVisibility(View.VISIBLE);
        } else {
            layoutTop.setVisibility(View.GONE);
        }

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (FaceBitmap.bitmap != null && !FaceBitmap.bitmap.isRecycled()) {
            FaceBitmap.bitmap.recycle();
            FaceBitmap.bitmap = null;
        }
        EventBus.getDefault().unregister(this);
        unbiner.unbind();
        unbiner = null;
    }

    /**
     * 获取相机权限
     */
    @TargetApi(Build.VERSION_CODES.M)
    private void checkPermission() {
        checkPermission(new CheckPermListener() {
            @Override
            public void superPermission() {
                Intent localIntent = new Intent(FaceIdentityActivity.this, FaceActivity.class);
                startActivityForResult(localIntent, 100);
            }

            @Override
            public void onReject() {

            }


        }, R.string.camera_storage_card_p, R.string.get_cammra, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(IdcardFaceEvent event) {
        if (FaceBitmap.bitmap != null) {
            uploadImg(ImageUtil.Bitmap2StrByBase64(FaceBitmap.bitmap, 100));  //上传颜值
        }
    }


    public void updateFace(String url) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        DealPhotoBean bean = new DealPhotoBean();
//        bean.deal_id = UserInfoGlobal.getDealId();
        bean.img = url;
        Api.api_service.getDealPhotoV3(bean).compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {

                    ToastUtil.makeText(getApplicationContext(), "上传成功", Toast.LENGTH_SHORT).show();
                    if (is_borrow_step) {
                        Util.startActivity(this, PhoneIdentityActivity.class);
                        finish();
                    } else {
                        finish();
                    }
                });
    }

    public void uploadImg(String img) {
        if (!Network.checkNetwork(this)) {
            ToastUtil.makeText(this, "网络连接失败").show();
            return;
        }
        loadingDialog.show();
        UploadImageBean bean = new UploadImageBean();
        bean.img = img;
        Api.api_service.uploadImg(bean).compose(RxLifeUtil.NocheckOn(this)).
                doFinally(() -> {
                    try {

                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    if (result.getStatus() == 1) {
                        updateFace(result.getUrl());
                    } else {
                        loadingDialog.dismiss();
                        ToastUtil.makeText(this, result.getMsg());
                    }
                });
    }


    @OnClick({R.id.btn_back, R.id.btn_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_submit:
                checkPermission();
                break;
        }
    }


}
